package src.tree;

import java.util.ArrayDeque;

public class no226 {//翻转二叉树

    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        //前后序遍历都可以，中序不可以
        swap(root);
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    public void swap(TreeNode root){
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }

    //中序遍历
    public TreeNode invertTree2(TreeNode root) {
        if (root == null) return null;
        invertTree2(root.left);
        swap(root);
        invertTree2(root.left);  //注意这课依旧处理左结点
        return root;
    }

    /*    4
    *   2   7
    * 1  3 6  9
    * 第一次处理2时，变为
    *     4
    *   2   7
    * 3  1 6  9
    * 第二次处理4时，变为
    *     4
    *   7   2
    *  6 9 3  1
    * 此时第二层已经交换了，所以不能处理右边了，要处理左边root.left
    *     4
    *   7   2
    *  9 6 3 1
    * */

    //迭代法
    public TreeNode invertTree3(TreeNode root) {
        if (root == null) return null;
        ArrayDeque<TreeNode> stack = new ArrayDeque<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            swap(node);
            if (node.right != null) stack.push(node.right);  //右结点先入栈
            if (node.left != null) stack.push(node.left);
        }
        return root;
    }

    //层序遍历
    //注意区分借助栈的迭代遍历 和 借助队列的层序遍历。迭代是深搜，层序是广搜。注意栈右node先进，队列左node先进
    public TreeNode invertTree4(TreeNode root) {
        if (root == null) return null;
        ArrayDeque<TreeNode> queue = new ArrayDeque<>();
        queue.push(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- > 0) {
                TreeNode node = queue.pop();
                swap(node);
                if (node.left != null) queue.push(node.left);
                if (node.right != null) queue.push(node.right);
            }
        }
        return root;

    }

}
